//import { sample, last } from 'lodash';
import { getSongOfId } from '@/api';
import { defineStore, storeToRefs } from 'pinia';
import { onMounted, onUnmounted, watch } from 'vue';
import { debounce, formatLyric } from '@/utils/format';
//import { useUserStore } from '@/store/user';

// const KEYS = {
// 	volume: 'PLAYER-VOLUME',
// };
export const useSongStore = defineStore({
	id: 'song',
	state: () => ({
		audio: new Audio(), // Audio实例化
		//loopType: 2, // 循环模式   0随机播放  1单曲循环  2列表循环
		/** 音乐信息 */
		songId: 0, // 音乐 ID
		songTitle: "", // 歌名
		songUrl: "", // 音乐 URL
		songPic: `/img/songPic/tubiao.jpg`, // 歌曲图片
		singerName: "", //  歌手名
		source:"",//歌曲来源
		lyric: [] as ILyric[], // 处理后的歌词数据
	
		/** 音乐播放信息 */
		isPlay: false, // 播放状态
		//playBtnIcon: Icon.BOFANG, // 播放状态的图标
		volume: 0, // 音量
		duration: 0, // 音乐总时长
		currentTime: 0, // 当前音乐的播放位置
		changeTime: 0, // 指定播放时刻
		autoNext: true, // 用于触发自动播放下一首
		/** 这里是代码另加的 */
		sliderInput: false, //是否正在拖动进度条
		ended: false, //是否播放结束
		muted: false, //是否静音
	
		/** 音乐列表信息 */
		currentPlayList: [] as ISong[], // 当前播放列表
		songDetails: null, // 单个歌单信息
		currentPlayIndex: -1, // 当前歌曲在歌曲列表的位置
		showPlayList: false,  //是否展示歌曲播放列表 
		showPopup: false, //是否全屏展示播放
	}),
	getters:{
		playListCount: (state) => {
			return state.currentPlayList.length;
		},
		thisIndex: (state) => {
			return state.currentPlayList.findIndex((song) => song.id === state.songId);
		},
		nextSong(state): ISong {
			const { thisIndex, playListCount } = this;
			if (thisIndex === playListCount - 1) {
				return state.currentPlayList[0];
			} else {
				const nextIndex: number = thisIndex + 1;
				return state.currentPlayList[nextIndex];
			}
		},
		prevSong(state): ISong {
			const { thisIndex } = this;
			if (thisIndex === 0) {
				//如果为0不好解决
				return state.currentPlayList[state.currentPlayList.length - 1];
			} else {
				const prevIndex: number = thisIndex - 1;
				return state.currentPlayList[prevIndex];
			}
		},
		//歌词的时间，这个有点不太理解
		lyricTime(state) {
			return state.currentTime * 1000;
		},
	},
	actions:{
		// 获取歌曲名
		getSongTitle(str:string) {			
			return str.split("-")[1];
		},		
		// 获取歌手名
		getSingerName(str:string) {
			return str.split("-")[0];
		},
		//根据id播放音乐
		async play(id:number){			
			if (id == this.songId) return;
			this.isPlay = true;

			const data = await getSongOfId(id);
			this.audio.src = `http://localhost:8080${data.songUrl}`;
			this.songUrl = `http://localhost:8080${data.songUrl}`;
			this.songId = id;
			this.songTitle = this.getSongTitle(data.name);
			this.singerName = this.getSingerName(data.name);
			this.songPic = data.songPic;
			this.lyric = formatLyric(data.lyric);
			this.audio.play().catch((err) => console.log('错误了',err));
		},
		//已有详细信息播放音乐，playlist中存放的是已有详细信息的，这里有修改的余地
		// playHasDetail(params:ISong){
		// 	if (params.id == this.songId) return;
		// 	this.isPlay = true;
		// 	this.audio.src = `http://localhost:8080${data.songUrl}`;
		// 	this.songUrl = `http://localhost:8080${data.songUrl}`;
		// 	this.songId = params.id;
		// 	this.songTitle = this.getSongTitle(params.name);
		// 	this.singerName = this.getSingerName(params.name);
		// 	this.songPic = params.songPic;
		// 	this.lyric = formatLyric(params.lyric);
		// 	this.audio.play().catch((err) => console.log('错误了',err));
		// },
		//播放切换
		togglePlay(){ //按钮切换
			this.isPlay = !this.isPlay;
			if(this.isPlay){
				this.audio.play();
			}else{
				this.audio.pause();
			}
			console.log("是否play",this.isPlay);
		},
		// 静音切换
		toggleMuted() {
			this.muted = !this.muted;
			this.audio.muted = this.muted;
		},
		//音量设置
		setVolume(n: number) {
			n = n > 100 ? 100 : n;
			n = n < 0 ? 0 : n;
			this.volume = n;
			this.audio.volume = n / 100;
			//localStorage.setItem('PLAYER-VOLUME', n.toString());这个是什么有待考究
		},
		// 修改播放时间
		onSliderChange(val: number) {
			this.currentTime = val;
			this.sliderInput = false;
			this.audio.currentTime = val;
		},
		// 播放时间拖动中
		onSliderInput() {
			this.sliderInput = true;
		},
		// 定时器，确保结束什么的
		// 为什么要定时监听呢，我认为结束这个还好，主要是比如现在时刻是无时无刻在变的，不可能同一时刻不变的
		interval() {
			if (this.isPlay && !this.sliderInput) {
				this.currentTime = this.audio.currentTime;
				this.duration = this.audio.duration;
				this.ended = this.audio.ended;
			}
		},
		//初始化一个声音
		init() {
			this.audio.volume = this.volume / 100;
		},
		// 播放结束，结束播放后
		playEnd() {
			console.log('播放结束');
			//先写在这，目前还未实现歌曲列表
			// switch (this.loopType) {
			// 	case 0:
			// 		this.randomPlay();
			// 		break;
			// 	case 1:
			// 		this.rePlay();
			// 		break;
			// 	case 2:
			// 		this.next();
			// 		break;
			// }
		},
		// 上一曲
		prev() {
			// console.log('上一曲');
			this.play(this.prevSong.id);
		},
		// 下一曲
		next() {
			this.play(this.nextSong.id);
			// console.log('下一曲');
			// if (this.loopType === 0) {
			// 	this.randomPlay();
			// } else {
			// 	this.play(this.nextSong.id);
			// }
		},		
		// 播放列表里面添加音乐
		addPlayList(replace: boolean, ...list: ISong[]) {
			if (replace) {
				this.currentPlayList = list;
				//localStorage.setItem('playList', JSON.stringify(list));
				return;
			}
			list.forEach((song) => {
				if (this.currentPlayList.filter((s) => s.id === song.id).length <= 0) {
					this.currentPlayList.push(song);
				}
			});
		},
		//清除数据
		clearPlayList() {
			this.songUrl = "";
			this.songId = 0;
			this.singerName="", //  歌手名
			this.source = "",//歌曲来源
			this.lyric = [], // 处理后的歌词数据
			this.songTitle = '';
			this.isPlay = false;
			this.sliderInput = false;
			this.ended = false;
			this.muted = false;
			this.currentTime = 0;
			this.currentPlayList = [] as ISong[];
			this.showPlayList = false;
			this.audio.load();
			setTimeout(() => {
				this.duration = 0;
			}, 500);
		},
		// 获取歌词
		// getLyricDetail(id: number) {
		// 	const { lrc } = await getLyric(id);
		// 	this.lyricArr = formatLyric(lrc.lyric);
		// },

	}
});
export const userPlayerInit = () => {
	let timer: NodeJS.Timer;
	const { init, interval, playEnd } = useSongStore();

	const { ended } = storeToRefs(useSongStore());

	// 调用防抖函数，防止调用两次接口
	const debouncedPlayEnd = debounce(playEnd, 200);

	//监听播放结束
	watch(ended, (ended) => {
		if (!ended) return;
		debouncedPlayEnd();
	});

	//   启动定时器
	onMounted(() => {
		init();
		console.log('启动定时器');
		timer = setInterval(interval, 100);
	});

	//   清除定时器
	onUnmounted(() => {
		console.log('清除定时器');
		clearInterval(timer);
	});
};
